<template>
  <div class="app-container">
    <!-- 顶部查询框 -->
    <div class="filter-container">
      <el-select
        v-model="value"
        class="filter-item"
        style="width: 110px; position: relative; left: 100px"
      >
        <el-option v-for="item in options" :key="item" :label="item.label" :value="item.value" />
      </el-select>
      <el-input
        v-model="listQuery.searchValue"
        placeholder="请输入查询信息"
        style="width: 200px; position: relative; left: 100px;margin-left: 10px"
        class="filter-item"
        @keyup.enter.native="getList"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        style="position: relative; left: 100px; margin-left: 10px"
        @click="getList"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style=" margin-left: 10px; position: relative; left: 100px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加门店
      </el-button>
    </div>

    <!-- 表格主体 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      :row-style="rowStyle"
    >

      <!-- id -->
      <el-table-column label="门店编号" prop="id" width="80" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column type="index" label="编号" width="170" align="center">
        </el-table-column> -->

      <!-- 店铺名称 -->
      <el-table-column label="门店名称" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.storeName }}</span>
        </template>
      </el-table-column>

      <!-- 店长 -->
      <el-table-column label="店长" width="160" align="center">
        <template slot-scope="{ row }">
          <el-popover trigger="hover" placement="top">
            <p>姓名: {{ row.manager.name }}</p>
            <p>性别: {{ row.manager.sex }}</p>
            <p>电话: {{ row.manager.phone }}</p>
            <p>邮箱: {{ row.manager.email }}</p>
            <div slot="reference" class="name-wrapper">
              <span>{{ row.manager.name }}</span>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <!-- 店铺面积 -->
      <el-table-column label="店铺面积(m²)" width="120" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.area }}</span>
        </template>
      </el-table-column>

      <!-- 地址 -->
      <el-table-column label="门店地址" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.address }}</span>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" width="350" align="center">
        <template slot-scope="{ row, $index}">
          <el-popover placement="left" width="500" trigger="click">
            <el-table :data="storeRuleList">
              <el-table-column width="80" property="id" label="序号" />
              <el-table-column width="380" property="storeExplain" label="规则描述" align="left" />
            </el-table>
            <el-button slot="reference" size="mini" type="info" @click="getRuleList(row)">查看门店规则</el-button>
          </el-popover>
          <el-button
            size="mini"
            type="primary"
            style="margin-left: 10px;"
            @click="handleEdit(row,$index )"
          >编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index )">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部分页功能 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :size.sync="listQuery.size"
      @pagination="getList"
    />

    <!-- 编辑门店展示页 -->
    <el-dialog title="编辑门店" :visible.sync="dialogFormVisible_update" width="40%">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        :hide-required-asterisk="true"
        style="width: 400px; margin-left: 50px"
      >
        <!-- 门店信息 -->
        <el-form-item label="店铺名称" prop="storeName">
          <el-input v-model="temp.storeName" />
        </el-form-item>
        <el-form-item label="店铺面积" prop="area">
          <el-input v-model.number="temp.area" />
        </el-form-item>
        <el-form-item label="店铺地址" prop="address">
          <el-input v-model="temp.address" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible_update = false"> 取消 </el-button>
        <el-button type="primary" @click="updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 添加门店展示页 -->
    <el-dialog :title="addtitle" :visible.sync="dialogFormVisible_add" width="40%">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        :hide-required-asterisk="true"
        style="width: 400px; margin-left: 50px"
      >
        <!-- 第一步 -->
        <div v-show="active==1">
          <!-- 门店信息 -->
          <el-form-item label="店铺名称" prop="storeName">
            <el-input v-model="temp.storeName" />
          </el-form-item>
          <el-form-item label="店铺面积" prop="area">
            <el-input v-model.number="temp.area" />
          </el-form-item>
          <el-form-item label="店铺地址" prop="address">
            <el-input v-model="temp.address" type="textarea" maxlength="255" :autosize="{minRows: 2}" />
          </el-form-item>
        </div>
        <!-- 第二步 -->
        <div v-show="active==2">
          <!-- 店长信息 -->
          <el-form-item label="店长姓名" prop="manager.name">
            <el-input v-model="temp.manager.name" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio v-model="temp.manager.sex" label="男">男</el-radio>
            <el-radio v-model="temp.manager.sex" label="女">女</el-radio>
          </el-form-item>
          <el-form-item label="手机" prop="manager.phone">
            <el-input v-model="temp.manager.phone" />
          </el-form-item>
          <el-form-item label="邮箱" prop="manager.email">
            <el-input v-model="temp.manager.email" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="active==2" type="primary" @click="back()">上一步</el-button>
        <el-button @click="dialogFormVisible_add = false"> 取消 </el-button>
        <el-button v-show="active==1" type="primary" @click="next()">下一步</el-button>
        <el-button v-show="active==2" type="primary" @click="createData()">
          确认
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  DeleteStore,
  fetchStoreList,
  addStore,
  getRuleListById,
  updateStore
} from '@/api/storeManage'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'

export default {
  name: '',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      // 根据关键字分页模糊查询门店
      options: [{
        value: 'id',
        label: '门店编号'
      }, {
        value: 'store_name',
        label: '门店名称'
      }, {
        value: 'area',
        label: '门店面积'
      }, {
        value: 'address',
        label: '门店地址'
      }],
      value: 'store_name',

      // 分页功能
      total: 0,
      listQuery: {
        // 当前页
        page: 1,
        // 每页大小
        size: 5,
        // 查询字段
        key: '',
        // 查询条件
        searchValue: ''
      },
      // 表格
      rowStyle: { height: '80px' },
      tableKey: 0,
      listLoading: false,

      // 门店数据
      list: null,
      storeRuleList: null,

      // 编辑添加展示页
      dialogFormVisible_add: false,
      dialogFormVisible_update: false,
      active: 1,
      addtitle: '添加门店',

      temp: {
        id: '',
        storeName: '',
        area: undefined,
        address: '',
        manager: {
          name: '',
          sex: '',
          phone: '',
          email: ''
        }
      },
      rules: {
        storeName: [{ required: true, message: '请输入店铺名称', trigger: 'blur' }],
        area: [
          { required: true, message: '请输入店铺面积', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' }],
        address: [{ required: true, message: '请输入店铺地址', trigger: 'blur' }],
        'manager.name': [{ required: true, message: '请输入店长名称', trigger: 'blur' }],
        'manager.phone': [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式错误',
            trigger: 'blur'
          }],
        'manager.email': [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式错误', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 分页获取门店信息
    getList() {
      this.listLoading = true
      this.listQuery.key = this.value
      // 获取店铺信息
      fetchStoreList(this.listQuery).then((res) => {
        // console.log("获取店铺后", res)
        if (res.returnValue === 1) {
          this.list = res.data.records
          this.total = res.data.total
          for (var item of this.list) {
            if (item.manager == null) {
              item.manager = this.temp.manager
            }
          }
          this.listLoading = false
        } else {
          this.list = []
          this.listLoading = false
          this.$notify({
            title: 'Error',
            message: res.msg,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    // 根据id查询门店规则
    getRuleList(row) {
      getRuleListById(row.id).then((res) => {
        if (res.returnValue === 1) {
          this.storeRuleList = res.data
          // 编辑规则描述
          this.editRuleExplain()
        } else {
          this.storeRuleList = []
          this.$notify({
            title: 'Error',
            message: res.msg,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    // 编辑店铺规则描述
    editRuleExplain() {
      var index = 0
      const data = this.storeRuleList
      for (var rule of data) {
        index += 1
        rule.id = index
        if (rule.ruleName === 'preWorkTime') {
          var value = rule.storeRuleValue
          var explain = '开店前' + value + '小时内做准备工作'
          rule.storeExplain = explain
        } else if (rule.ruleName === 'needPeopleParam') {
          var value = rule.storeRuleValue
          var explain = '预测客流量 / ' + value + ' = 需要店员数量'
          rule.storeExplain = explain
        } else if (rule.ruleName === 'minPeopleRequest') {
          var value = rule.storeRuleValue
          var explain = '没有客流时，至少需要' + value + '个员工值班'
          rule.storeExplain = explain
        } else if (rule.ruleName === 'closeWorkTime') {
          var value = rule.storeRuleValue
          var explain = '关店后' + value + '小时内做收尾工作'
          rule.storeExplain = explain
        } else if (rule.ruleName === 'closeStoreEmps') {
          var value = rule.storeRuleValue.split(',')
          var explain = '门店面积 / ' + value[0] + ' + ' + value[1] + ' = 收尾工作人数'
          rule.storeExplain = explain
        } else if (rule.ruleName === 'preWorkN') {
          var value = rule.storeRuleValue
          var explain = '门店面积 / ' + value + ' = 开店前准备工作需要人数'
          rule.storeExplain = explain
        }
      }
    },
    resetTemp() {
      this.temp = {
        id: '',
        storeName: '',
        area: undefined,
        address: '',
        manager: {
          name: '',
          sex: '男',
          phone: '',
          email: ''
        }
      }
    },
    handleCreate() {
      this.resetTemp()
      this.active = 1
      this.dialogFormVisible_add = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const newTotal = this.total + 1
          const returnTemp = {}
          this.total += 1
          this.temp.id = newTotal
          // returnTemp.id = this.temp.id
          returnTemp.storeName = this.temp.storeName
          returnTemp.area = this.temp.area
          returnTemp.address = this.temp.address
          returnTemp.manager = this.temp.manager
          // console.log("得到returnTemp", returnTemp)
          addStore(returnTemp).then((res) => {
            if (res.returnValue === 1) {
              this.getList()
              this.dialogFormVisible_add = false
              this.$notify({
                title: 'Success',
                message: res.data,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: 'Error',
                message: res.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleEdit(row, index) {
      // console.log("index=" + index, "row=" + row);
      this.temp = Object.assign({}, row)
      this.dialogFormVisible_update = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const returnTemp = {}
          returnTemp.id = this.temp.id
          returnTemp.storeName = this.temp.storeName
          returnTemp.area = this.temp.area
          returnTemp.address = this.temp.address
          // console.log("修改门店信息：", returnTemp);
          updateStore(returnTemp).then((res) => {
            // console.log(res);
            if (res.returnValue === 1) {
              this.getList()
              this.dialogFormVisible_update = false
              this.$notify({
                title: 'Success',
                message: res.data,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: 'Error',
                message: res.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该门店信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          DeleteStore(row.id).then((res) => {
            if (res.returnValue === 1) {
              this.$notify({
                title: 'Success',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$notify({
                title: 'Error',
                message: res.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 添加门店下一步、上一步操作
    next() {
      this.active = 2
      this.addtitle = '添加店长'
    },
    back() {
      this.active = 1
      this.addtitle = '添加门店'
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
